package com.crazymakercircle.queue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ArrayBlockingQueueReentrantLock{
	private Object[] array;		//数组
	private int takeIndex;			//头
	private int putIndex;			//尾
	private volatile int count;	//元素个数
	private ReentrantLock lock = new ReentrantLock();	//锁
	private Condition notEmpty = lock.newCondition();	//非空
	private Condition notFull = lock.newCondition();	//非满

	public ArrayBlockingQueueReentrantLock(int capacity){
		this.array = new Object[capacity];
	}

	//写入元素
	public void put(Object o) throws InterruptedException{
		try{
			lock.lock();
			//当队列满时，阻塞
			while(count == array.length){
				notFull.wait();
			}
			array[putIndex++] = o;
			if(putIndex == array.length){
				putIndex = 0;
			}
			count++;
			//唤醒线程
			notEmpty.notifyAll();
		}finally{
			lock.unlock();
		}
	}
	
	//取出元素
	public Object take() throws InterruptedException{
		 lock.lock();
		 try{
		 	//当队列为空，阻塞
		 	while(count == 0){
		 		notEmpty.wait();
		 	}
		 	Object o = array[takeIndex++];
		 	if(takeIndex == array.length){
		 		takeIndex = 0;
		 	}
		 	count--;
		 	//唤醒线程
		 	notFull.notifyAll();
		 	return o;
		 }finally{
		 	lock.unlock();
		 }
	}
}
